package com.haocean.project.scheduled;

import com.alibaba.fastjson.JSON;
import com.haocean.project.dao.CustomerDAO;
import com.haocean.project.model.Customer;
import com.haocean.project.model.dto.Page;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.retry.annotation.Backoff;
import org.springframework.retry.annotation.Retryable;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashSet;
import java.util.List;

/**
 * @Auther:wanghao
 * @Date: 2023/7/25,11:50
 * @Desc: 客户定时
 */
@Component
public class CustomerJobComponent {
    @Autowired
    private CustomerDAO customerDAO;
    /**
     * 定时重试
     */
    @Scheduled(cron = "0 0/10 * * * ?")
    @Retryable(value = Exception.class, maxAttempts = 3, backoff = @Backoff(delay = 2000L, multiplier = 1.5))
    public void CustomerJobComponent() {
       this.rollBACK();
    }
    /**
     * 出现错误回滚
     */
    @Transactional
    public  void rollBACK(){
        try {
            //调用接口获取数据
            CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
            HttpGet httpGet = new HttpGet("http://192.168.100.101:8080/api/customer/list?page=0");
            //token
            httpGet.setHeader("Authorization", "hvdduaax");
            CloseableHttpResponse execute = closeableHttpClient.execute(httpGet);
            HttpEntity entity = execute.getEntity();
            String s = EntityUtils.toString(entity);
            System.out.println(s);
            Page page1 = JSON.parseObject(s, Page.class);
            if (page1 != null) {
                String s1 = page1.getContent().toString();
                List<Customer> customerList = JSON.parseArray(s1, Customer.class);
                //利用set去重
                HashSet<Customer> customerSet = new HashSet<>(customerList);
                for (Customer customer : customerSet) {
                    //通过id查询 如果存在则更新 不存在则插入
                    Customer customerOne = customerDAO.selectByPrimaryKey(customer.getId());
                    if (customerOne != null) {
                        customerDAO.updateByPrimaryKey(customer);
                    }else{
                        customerDAO.insert(customer);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
